/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.st.validation;

import org.codehaus.groovy.grails.validation.AbstractConstraint
import org.springframework.validation.Errors

class PostalCodeConstraint extends AbstractConstraint {

    private static final String DEFAULT_MESSAGE_CODE = "default.postalCode.invalid.message";
    public static final String NAME = "postalCode";

    private boolean postalCode;

    private USA = { postalCode->
        postalCode ==~ /\d{5}((\-|\s)?\d{4})?/
    }

    private CA = { postalCode->
        postalCode ==~ /[A-Z]\d[A-Z] \d[A-Z]\d/
    }

    public void setParameter(Object constraintParameter) {
        if(!(constraintParameter instanceof Boolean))
        throw new IllegalArgumentException("Parameter for constraint ["
               +NAME+"] of property ["
               +constraintPropertyName+"] of class ["
               +constraintOwningClass+"] must be a boolean value");

        this.postalCode = ((Boolean)constraintParameter).booleanValue();
        super.setParameter(constraintParameter);
    }

    protected void processValidate(Object target, Object propertyValue, Errors errors) {
        if (!validPostalCode(target, propertyValue)) {
//            def args = (Object[]) [constraintPropertyName, constraintOwningClass,
//            propertyValue]
            super.rejectValue(target, errors, DEFAULT_MESSAGE_CODE);
        }
    }

    boolean supports(Class type) {
        return type != null && String.class.isAssignableFrom(type);
    }

    String getName() {
        return NAME;
    }

    boolean validPostalCode(target, propertyValue) {
        def country = "USA"
        if (target.metaClass.hasMetaProperty("country")) {
            country = target.country
        }
        this."$country"(propertyValue)
    }
}